package com.zoro.barn.business.service.system.business.user.controller;

import com.zoro.barn.business.service.system.business.user.entity.BarnUser;
import com.zoro.barn.business.service.system.business.user.exceptions.AccountAlreadyExistException;
import com.zoro.barn.business.service.system.business.user.service.BarnUserService;
import com.zoro.barn.commons.webcommons.tools.RequestUser;
import com.zoro.barn.commons.webcommons.tools.WebContentUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author zhaoxingwu
 */
@RestController
@RequestMapping("user")
public class BarnUserController {

    private final BarnUserService barnUserService;

    public BarnUserController(BarnUserService barnUserService) {
        this.barnUserService = barnUserService;
    }

    /**
     * 条件查询
     *
     * @param param 查询条件、
     * @return result
     */
    @RequestMapping("/query")
    public List<BarnUser> query(@RequestBody BarnUser param) {
        return this.barnUserService.query(param);
    }

    /**
     * @param data new data
     * @return saved data
     */
    @RequestMapping("/save")
    public BarnUser save(@RequestBody BarnUser data) {

        if (StringUtils.isBlank(data.getPid())) {
            // add
            // 查重
            BarnUser param = new BarnUser();
            param.setUserAccount(data.getUserAccount());
            List<BarnUser> old = this.barnUserService.query(param);
            if (CollectionUtils.isNotEmpty(old)) {
                throw new AccountAlreadyExistException(data.getUserAccount());
            }
            RequestUser user = WebContentUtil.requestUserInfo();
            data.setCreateId(user.getPid());
        } else {
            data.setUpdateId(WebContentUtil.requestUserInfo().getPid());
        }

        return this.barnUserService.save(data);

    }

    /**
     * pid
     *
     * @param pid pid
     * @return data
     */
    @RequestMapping(value = "/getById/{pid}", method = RequestMethod.GET)
    public BarnUser getById(@PathVariable("pid") String pid) {
        if (StringUtils.isBlank(pid)) {
            return null;
        }
        return this.barnUserService.getById(pid);
    }
}
